local Util = require('skywalking.util')
local encode_base64 = Util.encode_base64
local decode_base64 = Util.decode_base64

local Propagation = require('skywalking.propagation')
local Const = require('skywalking.constants')

local _M = {}

--@element
-- {
--     type = 'CROSS_PROCESS',
--     trace_id,
--     segment_id,
--     span_id,
--     parent_service,
--     parent_service_instance,
--     parent_endpoint,
--     address_used_at_client,
-- }

function _M.new()
    return setmetatable({ type = 'CROSS_PROCESS'}, { __index = _M})
end

function _M.decode(carrier)
    local ref = _M.new()
    if Propagation.DecodeSW8(ref, Const.HeaderKeySw8, carrier) then
        return ref
    end
end

function _M.encode(ref, injector)
    if not injector then
        return
    end
    Propagation.EncodeSW8(ref, Const.HeaderKeySw8, injector)
end

-- Return RefProtocol
function _M.transform(ref)
    local refBuilder = {}
    refBuilder.refType = 'CrossProcess'
    refBuilder.traceId = ref.trace_id
    refBuilder.parentTraceSegmentId = ref.parent_segment_id
    refBuilder.parentSpanId = ref.parent_span_id
    refBuilder.parentService = ref.parent_service
    refBuilder.parentServiceInstance = ref.parent_service_instance
    refBuilder.parentEndpoint = ref.parent_endpoint
    refBuilder.networkAddressUsedAtPeer = ref.address_used_at_client
    return refBuilder
end

return _M
